<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>软件工作量预估模型</title>
    <script src="../js/xlsx.full.min.js"></script>
    <link rel="stylesheet" href="../css/all.min.css">
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #fff;
            color: #333;
        }
        .container {
            margin: 0 auto;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
        }
        .button-group {
            display: flex;
            gap: 10px;
            margin-bottom: 15px;
            flex-wrap: wrap;
        }
        button {
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 8px;
            color: white;
            font-weight: 500;
        }
        #addRow {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        #addRow:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 8px rgba(0, 0, 0, 0.15);
        }
        #exportExcel {
            background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        #exportExcel:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 8px rgba(0, 0, 0, 0.15);
        }
        #importExcel {
            background: linear-gradient(135deg, #667eea 0%, #7254af 100%);
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        #importExcel:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 8px rgba(0, 0, 0, 0.15);
        }
        .delete-btn {
            background: linear-gradient(135deg, #6a70d7 0%, #6878e1 100%);
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            padding: 6px 12px;
        }
        .delete-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.15);
        }
        table {
            border-collapse: collapse;
            width: 100%;
            margin-bottom: 20px;
        }
        th, td {
            border: 1px solid #e0e0e0;
            padding: 12px 8px;
            text-align: center;
        }
        th {
            background-color: #3498db;
            color: white;
            font-weight: 500;
            position: sticky;
            top: 0;
            z-index: 10;
        }
        tr:nth-child(even) {
            background-color: #f8f9fa;
        }
        tr:hover {
            background-color: #f1f7fd;
        }
        .total-row {
            background-color: #e3f2fd !important;
            font-weight: bold;
        }
        .total-row:hover {
            background-color: #bbdefb !important;
        }
        input {
            width: 90%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            text-align: center;
            transition: border 0.3s;
        }
        input:focus {
            outline: none;
            border-color: #3498db;
            box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
        }
        input.total-workload {
            font-weight: bold;
            color: #2c3e50;
        }
        .stage-value {
            font-weight: 500;
            color: #27ae60;
        }
        .total-value {
            font-weight: bold;
            color: #1e88e5;
        }
        #fileInput {
            display: none;
        }
        .import-info {
            margin-top: 10px;
            padding: 10px;
            background-color: #e8f5e9;
            border-radius: 4px;
            color: #2e7d32;
            display: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="button-group">
            <button id="addRow">
                <i class="fas fa-plus-circle"></i>
                添加新行
            </button>
            <button id="importExcel">
                <i class="fas fa-file-import"></i>
                导入Excel
            </button>
            <button id="exportExcel">
                <i class="fas fa-file-excel"></i>
                导出Excel
            </button>
            <input type="file" id="fileInput" accept=".xlsx, .xls">
            <div class="import-info" id="importInfo"></div>
        </div>
        <table id="workloadTable">
            <thead>
                <tr>
                    <th>序号</th>
                    <th>系统</th>
                    <th>需求</th>
                    <th>功能描述</th>
                    <th>需求阶段</th>
                    <th>设计阶段</th>
                    <th>开发阶段</th>
                    <th>测试阶段</th>
                    <th>培训阶段</th>
                    <th>合计工作量（人天）</th>
                    <th>备注</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>1</td>
                    <td><input type="text" class="system"></td>
                    <td><input type="text" class="requirement"></td>
                    <td><input type="text" class="description"></td>
                    <td class="stage-value requirement-stage">0.00</td>
                    <td class="stage-value design-stage">0.00</td>
                    <td class="stage-value development-stage">0.00</td>
                    <td class="stage-value testing-stage">0.00</td>
                    <td class="stage-value training-stage">0.00</td>
                    <td><input type="number" class="total-workload" min="0" value="0" step="0.01"></td>
                    <td><input type="text" class="remark"></td>
                    <td><button class="delete-btn"><i class="fas fa-trash-alt"></i> 删除</button></td>
                </tr>
            </tbody>
            <tfoot>
                <tr class="total-row">
                    <td colspan="4">总计</td>
                    <td class="total-value" id="total-requirement">0.00</td>
                    <td class="total-value" id="total-design">0.00</td>
                    <td class="total-value" id="total-development">0.00</td>
                    <td class="total-value" id="total-testing">0.00</td>
                    <td class="total-value" id="total-training">0.00</td>
                    <td class="total-value" id="total-workload">0.00</td>
                    <td colspan="2"></td>
                </tr>
            </tfoot>
        </table>
    </div>

    <script>
        // 添加新行
        document.getElementById('addRow').addEventListener('click', function() {
            const tbody = document.querySelector('#workloadTable tbody');
            const rowCount = tbody.rows.length;
            const newRow = document.createElement('tr');
            
            newRow.innerHTML = `
                <td>${rowCount + 1}</td>
                <td><input type="text" class="system"></td>
                <td><input type="text" class="requirement"></td>
                <td><input type="text" class="description"></td>
                <td class="stage-value requirement-stage">0.00</td>
                <td class="stage-value design-stage">0.00</td>
                <td class="stage-value development-stage">0.00</td>
                <td class="stage-value testing-stage">0.00</td>
                <td class="stage-value training-stage">0.00</td>
                <td><input type="number" class="total-workload" min="0" value="0" step="0.01"></td>
                <td><input type="text" class="remark"></td>
                <td><button class="delete-btn"><i class="fas fa-trash-alt"></i> 删除</button></td>
            `;
            
            tbody.appendChild(newRow);
            
            // 为新添加的行绑定事件
            const newTotalInput = newRow.querySelector('.total-workload');
            newTotalInput.addEventListener('input', function() {
                calculateRow(newRow);
                updateTotals();
            });
        });

        // 删除行
        document.addEventListener('click', function(e) {
            if (e.target.classList.contains('delete-btn') || e.target.closest('.delete-btn')) {
                const row = e.target.closest('tr');
                row.remove();
                updateRowNumbers();
                updateTotals();
            }
        });

        // 自动计算函数
        function calculateRow(row) {
            const totalInput = row.querySelector('.total-workload');
            const total = parseFloat(totalInput.value) || 0;
            
            const requirementStage = row.querySelector('.requirement-stage');
            const designStage = row.querySelector('.design-stage');
            const developmentStage = row.querySelector('.development-stage');
            const testingStage = row.querySelector('.testing-stage');
            const trainingStage = row.querySelector('.training-stage');
            
            requirementStage.textContent = (total * 0.15).toFixed(2);
            designStage.textContent = (total * 0.08).toFixed(2);
            developmentStage.textContent = (total * 0.69).toFixed(2);
            testingStage.textContent = (total * 0.05).toFixed(2);
            trainingStage.textContent = (total * 0.03).toFixed(2);
        }

        // 更新总计
        function updateTotals() {
            const rows = document.querySelectorAll('#workloadTable tbody tr');
            
            let totalWorkload = 0;
            let totalRequirement = 0;
            let totalDesign = 0;
            let totalDevelopment = 0;
            let totalTesting = 0;
            let totalTraining = 0;
            
            rows.forEach(row => {
                const totalInput = row.querySelector('.total-workload');
                const total = parseFloat(totalInput.value) || 0;
                totalWorkload += total;
                
                totalRequirement += total * 0.15;
                totalDesign += total * 0.08;
                totalDevelopment += total * 0.69;
                totalTesting += total * 0.05;
                totalTraining += total * 0.03;
            });
            
            document.getElementById('total-workload').textContent = totalWorkload.toFixed(2);
            document.getElementById('total-requirement').textContent = totalRequirement.toFixed(2);
            document.getElementById('total-design').textContent = totalDesign.toFixed(2);
            document.getElementById('total-development').textContent = totalDevelopment.toFixed(2);
            document.getElementById('total-testing').textContent = totalTesting.toFixed(2);
            document.getElementById('total-training').textContent = totalTraining.toFixed(2);
        }

        // 更新行号
        function updateRowNumbers() {
            const rows = document.querySelectorAll('#workloadTable tbody tr');
            rows.forEach((row, index) => {
                row.cells[0].textContent = index + 1;
            });
        }

        // 为初始行的合计工作量输入框绑定事件
        document.querySelector('.total-workload').addEventListener('input', function() {
            const row = this.closest('tr');
            calculateRow(row);
            updateTotals();
        });

        // 为所有现有行绑定事件
        document.querySelectorAll('.total-workload').forEach(input => {
            input.addEventListener('input', function() {
                const row = this.closest('tr');
                calculateRow(row);
                updateTotals();
            });
        });

        // 导出Excel功能
        document.getElementById('exportExcel').addEventListener('click', function() {
            // 准备数据
            const table = document.getElementById('workloadTable');
            const rows = table.querySelectorAll('tbody tr');
            const data = [];
            
            // 添加表头
            const headers = [];
            table.querySelectorAll('thead th').forEach(header => {
                // 跳过操作列
                if (!header.textContent.includes('操作')) {
                    headers.push(header.textContent);
                }
            });
            data.push(headers);
            
            // 添加数据行
            rows.forEach(row => {
                const rowData = [];
                const cells = row.cells;
                
                for (let i = 0; i < cells.length; i++) {
                    // 跳过操作列（最后一列）
                    if (i === cells.length - 1) continue;
                    
                    const cell = cells[i];
                    if (cell.querySelector('input')) {
                        // 输入框内容
                        rowData.push(cell.querySelector('input').value);
                    } else {
                        // 普通文本内容
                        rowData.push(cell.textContent);
                    }
                }
                
                data.push(rowData);
            });
            
            // 添加总计行
            const totalRow = [
                '总计', '', '', '',
                document.getElementById('total-requirement').textContent,
                document.getElementById('total-design').textContent,
                document.getElementById('total-development').textContent,
                document.getElementById('total-testing').textContent,
                document.getElementById('total-training').textContent,
                document.getElementById('total-workload').textContent,
                ''
            ];
            data.push(totalRow);
            
            // 创建工作簿
            const wb = XLSX.utils.book_new();
            const ws = XLSX.utils.aoa_to_sheet(data);
            
            // 设置列宽
            const colWidths = [
                {wch: 8},    // 序号
                {wch: 15},   // 系统
                {wch: 20},   // 需求
                {wch: 25},   // 功能描述
                {wch: 12},   // 需求阶段
                {wch: 12},   // 设计阶段
                {wch: 12},   // 开发阶段
                {wch: 12},   // 测试阶段
                {wch: 12},   // 培训阶段
                {wch: 12},   // 合计工作量
                {wch: 20}    // 备注
            ];
            ws['!cols'] = colWidths;
            
            // 添加工作表到工作簿
            XLSX.utils.book_append_sheet(wb, ws, "工作量预估");
            
            // 导出Excel文件
            const date = new Date();
            const dateStr = date.getFullYear() + '-' + 
                           (date.getMonth() + 1).toString().padStart(2, '0') + '-' + 
                           date.getDate().toString().padStart(2, '0');
            XLSX.writeFile(wb, `工作量预估_${dateStr}.xlsx`);
        });

        // 导入Excel功能
        document.getElementById('importExcel').addEventListener('click', function() {
            document.getElementById('fileInput').click();
        });

        document.getElementById('fileInput').addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (!file) return;

            const reader = new FileReader();
            reader.onload = function(e) {
                try {
                    const data = new Uint8Array(e.target.result);
                    const workbook = XLSX.read(data, { type: 'array' });
                    
                    // 获取第一个工作表
                    const worksheet = workbook.Sheets[workbook.SheetNames[0]];
                    // 将工作表转换为JSON
                    const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
                    
                    // 处理导入的数据
                    processImportedData(jsonData);
                    
                    // 显示导入成功信息
                    const importInfo = document.getElementById('importInfo');
                    importInfo.textContent = `成功导入 ${jsonData.length - 1} 条数据`;
                    importInfo.style.display = 'block';
                    setTimeout(() => {
                        importInfo.style.display = 'none';
                    }, 3000);
                    
                } catch (error) {
                    alert('导入失败: ' + error.message);
                    console.error(error);
                }
            };
            reader.readAsArrayBuffer(file);
            
            // 重置文件输入，以便可以重复导入同一个文件
            e.target.value = '';
        });

        function processImportedData(data) {
            // 清空现有数据（保留表头）
            const tbody = document.querySelector('#workloadTable tbody');
            tbody.innerHTML = '';
            
            // 跳过表头行（第一行），从第二行开始处理数据
            for (let i = 1; i < data.length; i++) {
                const rowData = data[i];
                
                // 检查是否是空行
                if (rowData.every(cell => cell === undefined || cell === '')) continue;
                
                // 创建新行
                const newRow = document.createElement('tr');
                
                // 序号
                newRow.innerHTML += `<td>${i}</td>`;
                
                // 系统、需求、功能描述
                newRow.innerHTML += `<td><input type="text" class="system" value="${rowData[1] || ''}"></td>`;
                newRow.innerHTML += `<td><input type="text" class="requirement" value="${rowData[2] || ''}"></td>`;
                newRow.innerHTML += `<td><input type="text" class="description" value="${rowData[3] || ''}"></td>`;
                
                // 阶段值初始为0，后面会根据合计工作量计算
                newRow.innerHTML += `<td class="stage-value requirement-stage">0.00</td>`;
                newRow.innerHTML += `<td class="stage-value design-stage">0.00</td>`;
                newRow.innerHTML += `<td class="stage-value development-stage">0.00</td>`;
                newRow.innerHTML += `<td class="stage-value testing-stage">0.00</td>`;
                newRow.innerHTML += `<td class="stage-value training-stage">0.00</td>`;
                
                // 合计工作量（第10列，索引9）
                const totalWorkload = rowData[9] || 0;
                newRow.innerHTML += `<td><input type="number" class="total-workload" min="0" value="${totalWorkload}" step="0.01"></td>`;
                
                // 备注（第11列，索引10）
                newRow.innerHTML += `<td><input type="text" class="remark" value="${rowData[10] || ''}"></td>`;
                
                // 操作按钮
                newRow.innerHTML += `<td><button class="delete-btn"><i class="fas fa-trash-alt"></i> 删除</button></td>`;
                
                tbody.appendChild(newRow);
                
                // 为新行的合计工作量输入框绑定事件
                const totalInput = newRow.querySelector('.total-workload');
                totalInput.addEventListener('input', function() {
                    calculateRow(newRow);
                    updateTotals();
                });
                
                // 手动触发input事件以计算初始值
                totalInput.dispatchEvent(new Event('input'));
            }
            
            // 更新总计
            updateTotals();
        }
    </script>
</body>
</html>